﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SCMS.CoreBusinessLogic.Web;
using SCMS.CoreBusinessLogic.ActionFilters;
using SCMS.CoreBusinessLogic.Security;
using SCMS.UI.Models;
using SCMS.CoreBusinessLogic.FleetManager;
using SCMS.CoreBusinessLogic._Inventory;
using System.Text;
using SCMS.Model;
using System.Data.Objects.DataClasses;
using SCMS.CoreBusinessLogic.OrderRequest;
using SCMS.CoreBusinessLogic.TenderAnalysis;

namespace SCMS.UI.Controllers
{
    [MyException]
    public class FleetManagerController : PortalBaseController
    {
        private IOrderRequest ORService;
        private ITAnalysisService TAService;
        private IFleetDetailsService fleetservice;
        private InventoryService inventoryService;
        public FleetManagerController(IPermissionService permissionService, IUserContext userContext, IFleetDetailsService fleetservice,
            InventoryService inventoryService, IOrderRequest ORService, ITAnalysisService TAService)
            : base(userContext, permissionService)
        {
            this.ORService = ORService;
            this.TAService = TAService;
            this.fleetservice = fleetservice;
            this.inventoryService = inventoryService;
        }

        //
        // GET: /FleetManager/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult LoadFleetDetails(Guid? id = null)
        {
            using (var db = new SCMSEntities())
            {
                Guid fleetid = id.GetValueOrDefault();
                Model.FleetDetail fleetGnDetail = db.FleetDetails.FirstOrDefault(p => p.Id == fleetid);
                if (fleetGnDetail != null) foreach (var item in fleetGnDetail.GarageInfoes) { Currency c = item.Currency; Supplier s = item.Supplier; }
                if (fleetGnDetail != null) foreach (var item in fleetGnDetail.Equipment2Fleet) { FleetEquipment fe = item.FleetEquipment; }
                if (fleetGnDetail != null) foreach (var item in fleetGnDetail.DriverDetails) { Staff s = item.Staff; Person p = s.Person; }
                if (fleetGnDetail != null) foreach (var item in fleetGnDetail.FleetDailyManagements) { FleetMajorIncidence s = item.FleetMajorIncidence; }
                var model = new ViewFleetDetails()
               {
                   GarageInfoDetails = fleetGnDetail != null ? fleetGnDetail.GarageInfoes.OrderByDescending(s => s.Dateken).ToList() : new List<Model.GarageInfo>(),
                   Eqpmnt2FleetDetails = fleetGnDetail != null ? fleetGnDetail.Equipment2Fleet.ToList() : new List<Model.Equipment2Fleet>(),
                   FDailyMngtDetails = fleetGnDetail != null ? fleetGnDetail.FleetDailyManagements.OrderByDescending(s => s.IssueDate).ToList() : new List<Model.FleetDailyManagement>(),
                   DriverDetails = fleetGnDetail != null ? fleetGnDetail.DriverDetails.OrderByDescending(s => s.Staff.Person.FirstName).ToList() : new List<Model.DriverDetail>()
               };
                ViewBag.fleetId = id;
                ViewBag.AssetNo = fleetGnDetail != null ? "[" + fleetGnDetail.Asset.AssetNumber + "]" : "";
                return View("LoadFleetDetails", model);
            }

        }

        public ActionResult LoadNewFleetDetail(Guid? fleetId = null)
        {
            Guid fleetid = fleetId.GetValueOrDefault();
            Model.FleetDetail FDetails = fleetservice.GetGenFleetDetailsById(fleetid);
            var model = new FleetManager()
            {
                EntityFleetDetails = fleetId == null ? new Model.FleetDetail() : FDetails,
                Brands = new SelectList(fleetservice.GetVehicleMake(countryProg.Id), "Id", "Name", fleetId == null ? Guid.Empty : FDetails.VehicleModel != null ? FDetails.VehicleModel.VehicleMake.Id : Guid.Empty),
                Modelz = new SelectList(fleetservice.GetVehicleModel(fleetId == null ? Guid.Empty : FDetails.VehicleModel != null ? FDetails.VehicleModel.VehicleMake.Id : Guid.Empty), "Id", "Name"),
                Assets = new SelectList(inventoryService.GetAssetList(countryProg.Id, true, fleetId == null ? true : false), "Id", "Name"),
                InsuranceTypes = new SelectList(fleetservice.GetInsuranceTypes(countryProg.Id), "Id", "Name"),
                DutyTypes = new SelectList(fleetservice.GetDutyTypes(countryProg.Id), "Id", "Name")
            };
            ViewBag.Action = fleetId == null ? "SaveNewFleet" : "EditGenFleet";
            return View(model);
        }

        public ActionResult LoadNewDailyFleet(Guid id, Guid? dailyFleetInfoId = null)
        {
            Guid dailyFleetInfoid = dailyFleetInfoId.GetValueOrDefault();

            Model.FleetDailyManagement FDailyMgtDetails = fleetservice.GetDailyFleetById(dailyFleetInfoid);
            var model = new DailyFleetMgt()
            {
                EntityDailFM = dailyFleetInfoId == null ? new Model.FleetDailyManagement() : FDailyMgtDetails,
                Incidences = new SelectList(fleetservice.GetFleetIncidences(countryProg.Id), "Id", "Name")
            };
            model.EntityDailFM.FleetId = id;
            Model.FleetDailyManagement lastDailyFleet = dailyFleetInfoId == null ? fleetservice.GetLastDailyFleetRecord(id) : fleetservice.GetLastDailyFleetRecord(FDailyMgtDetails);
            if (dailyFleetInfoId == null) model.EntityDailFM.StartMilleage = lastDailyFleet != null ? lastDailyFleet.EndMilleage : null;
            ViewBag.LastMilleage = lastDailyFleet != null ? lastDailyFleet.EndMilleage : 0;
            ViewBag.CurrentStartMilleage = dailyFleetInfoId == null ? lastDailyFleet != null ? lastDailyFleet.EndMilleage : 0 : FDailyMgtDetails.EndMilleage;
            ViewBag.Action = dailyFleetInfoId == null ? "SaveNewDailyFleetMgt" : "EditDailyFleetMgt";
            return View(model);
        }

        public ActionResult LoadNewGarageInfo(Guid id, Guid? garageInfoId = null)
        {
            Guid garageInfoid = garageInfoId.GetValueOrDefault();
            Model.GarageInfo FGarageDetails = fleetservice.GetGarageInfoById(garageInfoid);
            var model = new GarageInfor()
            {
                EntityGarageInfo = garageInfoId == null ? new GarageInfo() : FGarageDetails,
                Currencies = new SelectList(ORService.GetCurrencies(countryProg.Id), "Id", "ShortName"),
                Suppliers = new SelectList(TAService.GetSuppliers(countryProg.Id), "Id", "Name"),
            };
            model.EntityGarageInfo.FleetId = id;
            ViewBag.Action = garageInfoId == null ? "SaveNewGarageInfo" : "EditGarageInfo";
            return View(model);
        }

        public ActionResult LoadNewDriverInfo(Guid id, Guid? driverInfoId = null)
        {
            Guid driverInfoid = driverInfoId.GetValueOrDefault();
            Model.DriverDetail FDriverDetails = fleetservice.GetDriverInfoById(driverInfoid);
            var model = new DriverInfo()
            {
                EntityDriverInfo = driverInfoId == null ? new DriverDetail() : FDriverDetails,
                Staff = new SelectList(TAService.GetStaffs(countryProg.Id), "StaffID", "StaffName")
            };
            model.EntityDriverInfo.FleetId = id;
            ViewBag.Action = driverInfoId == null ? "SaveNewDriverInfo" : "EditDriverInfo";
            return View(model);
        }

        public ActionResult LoadSummaryFleetDetails()
        {
            List<ViewFSummaryDetails> model = new List<ViewFSummaryDetails>();
            foreach (var item in fleetservice.GetFleetDetails(countryProg.Id))
            {
                var itemmodel = new ViewFSummaryDetails()
                {
                    EntityFleetDetails = item,
                    AvrgFuelConsumption = fleetservice.GetAverageFuelConsumed(item.Id)
                };
                model.Add(itemmodel);
            }
            return View(model);
        }

        public ActionResult LoadFleetAccecories(Guid id)
        {
            var model = new FleetAccesory()
            {
                EntityFleetAccesory = new Equipment2Fleet(),
                Accesories = new SelectList(fleetservice.GetFleetAccesories(countryProg.Id), "Id", "EquipmentName"),
                fleetId = id
            };
            return View(model);
        }

        public ActionResult GetAssetModel(Guid mkId)
        {
            StringBuilder blineOption = new StringBuilder();
            blineOption.Append("<select id=\"EntityFleetDetails_ModelId\" name=\"EntityFleetDetails.ModelId\"><option value=\"\">---Please Select---</option>");
            foreach (var item in fleetservice.GetVehicleModel(mkId))
                blineOption.Append("<option value=\"" + item.Id + "\">" + item.Name + "</option>");
            blineOption.Append("</select>");
            blineOption.Append("<span class=\"field-validation-valid\" data-valmsg-for=\"EntityFleetDetails.ModelId\" data-valmsg-replace=\"false\">Required</span>");
            ViewBag.Html = blineOption.ToString();
            return View("HTMLResponse");

        }

        [HttpPost]
        public ActionResult SaveNewFleet(FleetManager entitymodel)
        {
            entitymodel.EntityFleetDetails.Id = Guid.NewGuid();
            entitymodel.EntityFleetDetails.CountryProgrammeId = countryProg.Id;
            fleetservice.IsFleetDetailsSaved(entitymodel.EntityFleetDetails);
            return LoadFleetDetails();
        }

        [HttpPost]
        public ActionResult SaveNewDailyFleetMgt(DailyFleetMgt entitymodel)
        {
            entitymodel.EntityDailFM.Id = Guid.NewGuid();
            entitymodel.EntityDailFM.IssueDate = DateTime.Now;
            fleetservice.IsDailyFleetSaved(entitymodel.EntityDailFM);
            return LoadFleetDetails(entitymodel.EntityDailFM.FleetId);
        }

        [HttpPost]
        public ActionResult SaveNewGarageInfo(GarageInfor entitymodel)
        {
            entitymodel.EntityGarageInfo.Id = Guid.NewGuid();
            entitymodel.EntityGarageInfo.IssueDate = DateTime.Now;
            entitymodel.EntityGarageInfo.IfServiceNextMilleage = entitymodel.EntityGarageInfo.IfServiceCurrentMilleage + entitymodel.EntityGarageInfo.IfServiceNextMilleage;
            fleetservice.IsGarageInfoSaved(entitymodel.EntityGarageInfo);
            return LoadFleetDetails(entitymodel.EntityGarageInfo.FleetId);
        }

        [HttpPost]
        public ActionResult SaveNewDriverInfo(DriverInfo entitymodel)
        {
            entitymodel.EntityDriverInfo.Id = Guid.NewGuid();
            fleetservice.IsDriverInfoSaved(entitymodel.EntityDriverInfo);
            return LoadFleetDetails(entitymodel.EntityDriverInfo.FleetId);
        }

        [HttpPost]
        public ActionResult AddNewAccesory(FleetAccesory entitymodel)
        {
            entitymodel.EntityFleetAccesory.Id = Guid.NewGuid();
            entitymodel.EntityFleetAccesory.FleetId = entitymodel.fleetId;
            fleetservice.IsAccesoryAdded(entitymodel.EntityFleetAccesory);
            return LoadFleetDetails(entitymodel.fleetId);
        }

        public ActionResult EditGenFleet(FleetManager entitymodel)
        {
            fleetservice.IsFleetDetailsEdited(entitymodel.EntityFleetDetails);
            return LoadFleetDetails();
        }

        public ActionResult EditDriverInfo(DriverInfo entitymodel)
        {
            fleetservice.IsDriverInfoEdited(entitymodel.EntityDriverInfo);
            return LoadFleetDetails(entitymodel.EntityDriverInfo.FleetId);
        }

        public ActionResult EditGarageInfo(GarageInfor entitymodel)
        {
            fleetservice.IsGarageInfoEdited(entitymodel.EntityGarageInfo);
            return LoadFleetDetails(entitymodel.EntityGarageInfo.FleetId);
        }

        public ActionResult EditDailyFleetMgt(DailyFleetMgt entitymodel)
        {
            fleetservice.IsDailyFleetEdited(entitymodel.EntityDailFM);
            return LoadFleetDetails(entitymodel.EntityDailFM.FleetId);
        }

        public ActionResult DeleteFleet(Guid fleetId)
        {
            fleetservice.IsFleetDeleted(fleetId);
            return LoadFleetDetails();
        }

        public ActionResult DeleteDailyFleetInfo(Guid dailyFleetInfoId, Guid fleetId)
        {
            fleetservice.IsDailyFleetInfoDeleted(dailyFleetInfoId);
            return LoadFleetDetails(fleetId);
        }

        public ActionResult DeleteGarageInfo(Guid garageInfoId, Guid fleetId)
        {
            fleetservice.IsGarageInfoDeleted(garageInfoId);
            return LoadFleetDetails(fleetId);
        }

        public ActionResult DeleteDriverInfo(Guid driverInfoId, Guid fleetId)
        {
            fleetservice.IsDriverInfoDeleted(driverInfoId);
            return LoadFleetDetails(fleetId);
        }

        public ActionResult RemoveAccesory(Guid accesoryId, Guid fleetId)
        {
            fleetservice.IsAccesoryRemoved(accesoryId);
            return LoadFleetDetails(fleetId);
        }
    }
}
